package com.cqupt.utils.BaiduTransUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @Description //翻译配置设置
* @Date 16:42 2021/1/29
* @Param
**/
public class TransApi{
    /**
     * API主机
     */
    public static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    /**
     * BAIDU_FROM 翻译前语言
     */
    public static String BAIDU_FROM = "en";

    /**
     * BAIDU_TO 转换后语言
     */
    public static String BAIDU_TO = "zh";

    /**
     * dst
     */
    public static String BAIDU_DST = "dst";

    /**
     * APP_ID
     */
    public static String APP_ID = "20201229000658960";

    /**
     * SECURITY_KEY
     */
    public static String SECURITY_KEY = "I1QcJSlTnU8_lNWcuC7S";

    /**
     * 翻译接口
     * @param query 翻译目标值
     * @return  翻译结果
     */
    public static String getTransResult(String query) {
        Map<String, String> params = buildParams(query, BAIDU_FROM, BAIDU_TO);
        String transResult = HttpGet.get(TRANS_API_HOST, params);
        JSONObject jsonObject = JSON.parseObject(transResult);
        Object trans_result = jsonObject.get("trans_result");
        String s = JSON.toJSONString(trans_result, SerializerFeature.WriteClassName);
        List<Map<String,Object>> list = JSON.parseObject(s, List.class);
        StringBuffer retResult = new StringBuffer();
        if (!CollectionUtils.isEmpty(list)){
            for (Map<String,Object> trs : list){
                if (!StringUtils.isEmpty(trs.get(BAIDU_DST)))
                    retResult.append(trs.get(BAIDU_DST));
            }
        }
        return retResult.toString();
    }

    /**
     * 狗构建参数
     * @param query
     * @param from
     * @param to
     * @return
     */
    private static Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        //添加百度通用翻译api入参
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", APP_ID);
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = APP_ID + query + salt + SECURITY_KEY; // 加密前的原文
        try {
            params.put("sign", MD5.md5(src));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return params;
    }

}
